import Vue from 'vue'
import IframeComponent from './iframe.vue'

// 创建弹窗构造函数 - renamed to start with capital letter
const IframeConstructor = Vue.extend(IframeComponent)
window.IframeConstructor = IframeConstructor

// 创建弹窗组件实例的方法
function createInstance() {
    const instance = new IframeConstructor({
        el: document.createElement('div')
    })
    document.body.appendChild(instance.$el)
    return instance
}

// 注册全局弹窗方法
window.$modalIframe = {
    show(options = {}) {
        const instance = createInstance()
        // 合并配置项
        Object.assign(instance.$data, options)
        // 设置标题
        if (options.title) {
            instance.modalTitle = options.title
        }
        // 设置回调函数
        if (options.onClose) {
            instance.onClose = options.onClose
        }

        if (options.onConfirm) {
            instance.onConfirm = options.onConfirm
        }

        if (options.modalWidth) {
            instance.modalWidth = options.modalWidth
        }

        if (options.iframeUrl) {
            instance.iframeUrl = options.iframeUrl
        }

        if (options.isFooter) {
            instance.isFooter = options.isFooter
        }

        if (options.dom) {
            instance.dom = options.dom
        }

        if (options.confirmText) {
            instance.confirmText = options.confirmText
        }

        if (options.cancelText) {
            instance.cancelText = options.cancelText
        }

        console.log(options)
        if (options.isFooter) {
            instance.isFooter = options.isFooter
        }

        instance.iframeVisible = true
        window.modalIframeInstance = instance
        return instance
    },

    hide() {
        if (window.modalIframeInstance) {
            // 调用关闭回调
            if (typeof window.modalIframeInstance.onClose === 'function') {
                window.modalIframeInstance.onClose()
            }
            window.modalIframeInstance.iframeVisible = false
            // 延迟移除DOM
            setTimeout(() => {
                if (window.modalIframeInstance && window.modalIframeInstance.$el && window.modalIframeInstance.$el.parentNode) {
                    document.body.removeChild(window.modalIframeInstance.$el)
                    window.modalIframeInstance.$destroy()
                    window.modalIframeInstance = null
                }
            }, 300)
        }
    }
}






// 注册为Vue插件
export default {
    install(Vue) {
        Vue.prototype.$modalIframe = window.$modalIframe
    }
}